package app

import (
	"context"
	"encoding/json"
	"gitee.com/Luna-CY/hui-hui/internal/runtime"
	"os"
)

func (cls *Application[C]) LockConfig() {
	cls.mutex.Lock()
}

func (cls *Application[C]) UnlockConfig() {
	cls.mutex.Unlock()
}

// GetConfig 获取配置对象
func (cls *Application[C]) GetConfig() *C {
	return cls.config
}

// SetConfig 覆盖配置对象
func (cls *Application[C]) SetConfig(config *C) {
	cls.config = config
}

// LoadFromDisk 从磁盘加载配置
func (cls *Application[C]) LoadFromDisk(_ context.Context, path string) error {
	cf, err := os.Open(path)
	if nil != err && !os.IsNotExist(err) {
		return err
	}

	if os.IsNotExist(err) {
		return nil
	}

	defer func() {
		_ = cf.Close()
	}()

	if err := json.NewDecoder(cf).Decode(cls.config); nil != err {
		return err
	}

	return nil
}

// SyncToDisk 同步配置到磁盘
func (cls *Application[C]) SyncToDisk(_ context.Context, path string) error {
	if err := os.MkdirAll(runtime.ConfigRoot, 0755); nil != err {
		return err
	}

	f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	if nil != err {
		return err
	}

	defer func() {
		_ = f.Close()
	}()

	if err := json.NewEncoder(f).Encode(cls.config); nil != err {
		return err
	}

	return nil
}
